{% load static %}
<!DOCTYPE html>
<html>
<head>
    <title>上传库存文件</title>
</head>
<body>
    <h2>上传库存文件</h2>
    {% if error %}
        <p style="color: red;">{{ error }}</p>
    {% endif %}
    <form method="post" enctype="multipart/form-data" action="{% url 'stock_management' %}">
        {% csrf_token %}
        <input type="file" name="file" accept=".xlsx" required />
        <button type="submit">上传</button>
    </form>
</body>
<script>
function uploadStock() {
    const fileInput = document.getElementById('stockFileInput');
    const file = fileInput.files[0];
    if (!file) {
        alert("请选择一个文件");
        return;
    }

    const formData = new FormData();
    formData.append('file', file);

    fetch('/stock/', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': getCookie('csrftoken')  // 确保携带 CSRF Token
        }
    })
    .then(response => response.text())
    .then(data => {
        console.log("上传成功", data);
        window.location.href = "/display-stock/";  // 跳转到展示页
    })
    .catch(error => {
        console.error("上传失败", error);
        alert("上传失败：" + error);
    });
}

// 获取 Cookie 中的 csrftoken
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>
</html>
